<template>
	<view class="content">
		<view class="row b-b">
			<text class="tit">联系人</text>
			<input class="input" type="text" v-model="addressData.receiveName" placeholder="收货人姓名" placeholder-class="placeholder" />
		</view>
		<view class="row b-b">
			<text class="tit">手机号</text>
			<input class="input" type="number" v-model="addressData.receivePhone" placeholder="收货人手机号码" placeholder-class="placeholder" />
		</view>






		<view class="row picker-row b-b">
			<text class="tit">省市区</text>
			
			<view class="picker-v">
				<picker mode="multiSelector" :range="addressAllArray" range-key="name" :value="valueArray" @columnchange="bindColumnChange" @change="bindAddressChange">
					<view class="uni-input">{{addressData.pcaName_page}}</view>
				</picker>
			</view>
			
		</view>
		<view class="row b-b"> 
			<text class="tit">详细地址</text>
			<input class="input" type="text" v-model="addressData.detailAddress" placeholder="请输入详细地址" placeholder-class="placeholder" />
		</view>
		
		<view class="row default-row">
			<text class="tit">设为默认</text>
			<switch :checked="addressData.default" color="#008B8B" @change="switchChange" />
		</view>
		<button class="add-btn" @click="confirm">提交</button>
	</view>
</template>

<script>
	import areaJosn from '@/components/area.js'
	// import pickerAddress from '../../components/wangding-pickerAddress/wangding-pickerAddress.vue'
	// import AllAddress from '../../components/wangding-pickerAddress/data.js'
	import {_addaddress} from '@/service/shop.js'
	
	import { _searchaddress} from '@/service/shop.js'
	export default {
		data() {
			return {
				testForm:areaJosn ,// ceshi 
				initAddressTree: [],
				addressAllArray: [],
				valueArray: [0, 0, 0],
				noEndValueArray: [0, 0, 0],
				addressData: {
					accountNum:'',
					id: '',
					receiveName: '', // 联系人
					receivePhone: '', // 手机号
					pcaName: '',
					pcaName_page: '',
					pcaId: '',
					detailAddress: '', // 详细地址
					default: true,
					status: 0, // 如果选择为默认地址则为0
					isFirst: true, // 是否是第一次选择地址
				},
			}
		},
		computed: {
			shopId () {
				// #ifdef H5
				var reg = new RegExp("(^|&)state=([^&]*)(&|$)", "i");
				var r = window.location.search.substr(1).match(reg)[2];
				let url;
				if (r === '10') // 如果是螃蟹的，因为印刷的二维码不对，这里只能兼任写死
				{
					url = r + window.location.host;
				}
				else
				{
					url = r.split('_')[0] + window.location.host;
				}	
				return uni.getStorageSync(`SHOPID_`+url) || '';
				// #endif
				 //#ifdef APP-PLUS
				let {shopIdApp} = this.$json('appPublic');
				return shopIdApp;
			 //#endif	
			}
		},
		watch: {
			'addressData.default' (v) {
				this.addressData.status = v ? 0 : 1;
			}
		},
		onLoad(option){
			// #ifdef H5
			this.isFirst = true;
			// #endif
			let title = '新增收货地址';
			if(option.type==='edit'){
				title = '编辑收货地址'
				this.addressData = JSON.parse(option.data);
				console.log(option);
			}
			this.manageType = option.type;
			uni.setNavigationBarTitle({
				title
			});
			this.getPCA();
		},
		created(){
			let newdata;
			try {
				const value = uni.getStorageSync('userInfo');
				console.log(value)
				if (value) {
					newdata = value;
					if (newdata != null){
						{
							this.addressData.accountNum=newdata.accountNum
						}
					}
				}
			} catch (e) {
				console.error(e);
			}
		},
		methods: {
			getPCA() {
				if (this.testForm) {
					let data = this.testForm.data[0].children;
					this.initAddressTree = JSON.parse(JSON.stringify(data));
					if (this.addressData.pcaId) {
						let arr = this.addressData.pcaId.split(',');
						let addArr = [];
						let vArr = [];
						addArr.push(data);
						for (let i = 0; i < data.length; i++) {
							if (data[i].id === arr[0]) {
								vArr.push(i);
								addArr.push(data[i].children);
								for (let j = 0; j < data[i].children.length; j++) {
									if (data[i].children[j].id === arr[1]) {
										vArr.push(j);
										addArr.push(data[i].children[j].children);
										for (let k = 0; k < data[i].children[j].children.length; k++) {
											if (data[i].children[j].children[k].id === arr[2]) {
												vArr.push(k);
												break;
											}
										}
									}
								}
							}
						}
						this.addressAllArray = addArr;
						this.valueArray = vArr;
					} else {
						this.addressAllArray = [data, data[0].children, data[0].children[0].children];
						this.valueArray = [0, 0, 0];
					}
				} else {
					this.initAddressTree = [];
					this.addressAllArray = [];
				}
			},
			// 选择省市区，动态改变选项
			bindColumnChange (event) {
				// this.$nextTick(() => {
					console.log('columnChange:', event);
					console.log(event.detail);
					let {column, value} = event.detail;
					
					this.valueArray.splice(column, 1, value);
					let t = this.initAddressTree;
					if (column === 0) {
						this.addressAllArray = [t, t[value].children, t[value].children[0].children];
					} else if (column === 1) {
						this.addressAllArray = [t, t[this.noEndValueArray[0]].children, t[this.noEndValueArray[0]].children[value].children];
					}
					this.noEndValueArray[column] = value;
					// console.log(this.addressAllArray, this.noEndValueArray);
				// });
			},
			// 完成省市区选择
			bindAddressChange (e){
				console.log('change:', e);
				// #ifdef H5
				if (this.isFirst) {
					this.isFirst = false;
					this.valueArray = this.noEndValueArray;
				} else {
					this.valueArray = e.detail.value;
					this.noEndValueArray = e.detail.value;
				}
				// #endif
				// #ifdef APP-PLUS
				this.valueArray = e.detail.value;
				this.noEndValueArray = e.detail.value;
				// #endif
				let v = this.valueArray;
				let names = [this.addressAllArray[0][v[0]]['name'], this.addressAllArray[1][v[1]]['name'], this.addressAllArray[2][v[2]]['name']];
				let ids = [this.addressAllArray[0][v[0]]['id'], this.addressAllArray[1][v[1]]['id'], this.addressAllArray[2][v[2]]['id']];
				this.addressData.pcaName = names.join(',');
				this.addressData.pcaName_page = names.join(' ');
				this.addressData.pcaId = ids.join(',');
			},
			
			switchChange(e){
				console.log('switchChange: ', e);
				this.addressData.default = e.detail.value;
				console.log(this.addressData.default)
			},
			
			//地图选择地址
			chooseLocation(){
				uni.chooseLocation({
					success: (data)=> {
						console.log(data);
						let {address, name, longitude, latitude} = data;
						this.addressData.addressName = data.address;
						this.addressData.address = data.address;
					}
				})
			},
			
			//提交
			confirm(){
				let data = this.addressData;
				if(!data.receiveName){
					this.$api.msg('请填写收货人姓名');
					return;
				}
				if(!data.receivePhone){
					this.$api.msg('请填写手机号码');
					return;
				}
				if(!data.pcaId){
					this.$api.msg('请选择省市区');
					return;
				}
				if(!data.detailAddress){
					this.$api.msg('请填写详细地址');
					return;
				}
				// let url = '/receiveAdderss/save';
				// if (this.manageType === 'edit') {
				// 	url = '/receiveAdderss/update';
				// }
				// this.$https.post(url, {...data, shopId: this.shopId}).then((res) => {
				// 	if (!res.data.success) {
				// 		this.$api.msg(res.data.message);
				// 	} else {
				// 		this.$api.msg(`地址${this.manageType=='edit' ? '修改': '添加'}成功`);
				// 		this.$api.prePage().getAddress();
				// 		uni.navigateBack();
				// 	}
				// }).catch(error => console.log(error));
				// //this.$api.prePage()获取上一页实例，可直接调用上页所有数据和方法，在App.vue定义
				// this.$api.prePage().refreshList(data, this.manageType);
				// this.$api.msg(`地址${this.manageType=='edit' ? '修改': '添加'}成功`);
				// setTimeout(()=>{
				// 	uni.navigateBack()
				// }, 800)
				this.addaddress()
				uni.navigateBack({
					url:'/pages/address/address'
				})
			},
			
			async addaddress(){
				let data={
					account_user:this.addressData.accountNum,
					account_address:this.addressData.receivePhone,
					username_address:this.addressData.receiveName,
					pro_city:this.addressData.pcaName_page,
					addressdetail:this.addressData.detailAddress,
					isdefault:this.addressData.default
				}
				// console.log(this.addressData.accountNum)
				// console.log(this.addressData.accountNum+'|'+this.addressData.receivePhone+'|'+
				// this.addressData.receiveName+'|'+this.addressData.pcaName_page+'|'+this.addressData.detailAddress
				// +'|'+this.addressData.default)
				let res=await _addaddress(data)
				this.$api.msg('地址添加成功！')
				console.log(data)
				console.log(res)
			},
			
			//查询收货地址
			async searchaddress(){
				let data={
					account_user:this.addressData.accountNum
				}
				let res=await _searchaddress(data)
				console.log(res)
				console.log(data)
				this.addressList=res.data
			}
		}
	}
</script>

<style lang="scss" scoped>
	page{
		background: $page-color-base;
		padding-top: 16upx;
	}

	.row{
		display: flex;
		align-items: center;
		position: relative;
		padding:0 30upx;
		height: 110upx;
		background: #fff;
		
		.tit{
			flex-shrink: 0;
			width: 146upx;
			font-size: 30upx;
			// color: $font-color-dark;
		}
		.input{
			flex: 1;
			font-size: 30upx;
			// color: $font-color-dark;
		}
		.icon-shouhuodizhi{
			font-size: 36upx;
			// color: $font-color-light;
		}
		&.picker-row{
			font-size: 0;
			.picker-v{
				flex: 1;
				height: 30upx;
				picker{
					height: 100%;
					width: 100%;
				}
				.uni-input{
					font-size: 30upx;
					// color: $font-color-dark;
				}
			}
		}
	}
	.default-row{
		margin-top: 16upx;
		.tit{
			flex: 1;
		}
		switch{
			transform: translateX(16upx) scale(.9);
		}
	}
	.add-btn{
		display: flex;
		align-items: center;
		justify-content: center;
		width: 690upx;
		height: 80upx;
		margin: 60upx auto;
		color: #fff;
		background-color: #138f87;
		border-radius: 56.25rpx;
	}
</style>
